<?php

namespace app\admin\controller;

use app\base\model\User;
use app\common\controller\AdminBase;
use think\Exception;
use think\Request;
use think\Config;

class Test extends AdminBase {
  protected $model, $modelConfig, $modelQuestion, $modelUser;

  public function __construct(Request $request = NULL) {
    parent::__construct($request);
    $this->modelConfig = new \app\admin\model\Config();
    $this->modelQuestion = new \app\admin\model\Question();
    $this->modelUser = new User();
    $this->model = new \app\admin\model\Test();
  }

  public function _initialize() {
    parent::_initialize();
  }

  public function index() {
    $row = $this->modelConfig->getNewest();
    $qType = config('question')['type'];
    $qConfig = $row ? json_decode($row['q_config'], TRUE) : NULL;

    $rows = $this->model->paginate();

    return view('', [
      'rows'    => $rows,
      'qConfig' => $qConfig,
      'qType'   => $qType,
    ]);
  }

  public function add() {
    $config = $this->modelConfig->getNewest();
    if (!$config) $this->error('管理员尚未设定题库，无法新建考试 ');

    $qType = config('question')['type'];
    $qConfig = json_decode($config['q_config'], TRUE);
    $questions = [];
    foreach ($qConfig as $type => $v) {
      //获取各个类型中有效的题目数量
      $map = ['type'    => $type,
              'disable' => 0];
      $questions[ $type ] = $this->modelQuestion->where($map)->column('id');
      if (count($questions[ $type ]) < $v['num']) {
        $this->error('题库中题目数量小于试卷中要求的数量，无法生成数据。' . $qType[ $type ] . count($questions[ $type ]));
      }
    }
    $data = [];
    for ($i = 0; $i < 5; $i++) {
      $paper = [];
      foreach ($qConfig as $type => $v) {
        shuffle($questions[ $type ]);
        $paper = array_merge($paper, array_slice($questions[ $type ], 0, (int)$v['num']));
      }
      $data[] = [
        'q_config'      => $config['q_config'],
        'pass_score'    => $config['pass_score'],
        'exam_duration' => $config['exam_duration'],
        'questions'     => json_encode($paper),
      ];
    }
    //
    $ids = [];
    try {
      $ids = $this->model->saveAll($data);
    } catch (Exception $e) {
      $this->error($e->getMessage());
    }
    cmf_log('新增模拟考试', $ids);
    $this->success(lang('success'), url('index'));
  }

  public function disable() {
    $id = input('id/d', 0, 'abs');
    $row = ($id > 0) ? $this->model->find($id) : NULL;
    if (!$row) $this->error(lang('data empty'));

    $data = ['status' => !$row['status']];
    try {
      $this->model->allowField(TRUE)->save($data, ['id' => $row['id']]);
    } catch (Exception $e) {
      $this->error($e->getMessage());
    }
    cmf_log('启用/禁用模拟考试', $id);
    $this->success(lang('success'));
  }


}